#include "myfile.h"



_FILE* _fopen(const char*path,const char*mode){
    int fd=0;
    if(strcmp("w",mode)==0){
        fd=open(path,O_WRONLY|O_CREAT|O_TRUNC,0666);
    }
    else if(strcmp("r",mode)==0){
        fd=open(path,O_RDONLY,0666);
    }
    else if(strcmp("a",mode)==0){
        fd=open(path,O_WRONLY|O_CREAT|O_APPEND,0666);
    }
    else{
        return NULL;
    }

    _FILE* fp=(_FILE*)malloc(sizeof(_FILE));
    fp->fileno=fd;
    fp->flag=FLUSH_LINE;   //刷新方式默认为行刷新
    fp->outpos=0;

    return fp;
}
int _fwrite(const void*ptr,int size,_FILE* fp){
    //不考虑
    //"hello\n"
    //1.把内容加载到"c语言的缓冲区"
    memcpy(&fp->outbuffer[fp->outpos],ptr,size);
    fp->outpos+=size;
    //2.判断文件的刷新方式
    if(fp->flag & FLUSH_NOW){
        write(fp->fileno,fp->outbuffer,fp->outpos);
        fp->outpos=0;
    }
    else if(fp->flag & FLUSH_LINE){
        //找到第一个'\n'
        int i=0;
        while(i<fp->outpos && fp->outbuffer[i++]!='\n'){}
        if(fp->outbuffer[i-1]!='\n'){
            //没有'\n'
            return 0;
        }
        else{
            write(fp->fileno,fp->outbuffer,i);
            memmove(&fp->outbuffer[0],&fp->outbuffer[i],SIZE-i);
            fp->outpos-=i;
        }
    }
    else if(fp->flag & FLUSH_ALL){
        if(fp->outpos==SIZE){
            write(fp->fileno,fp->outbuffer,SIZE);
            fp->outpos=0;
        }
    }
    return size;
}
int _fclose(_FILE* fp){
    _fflush(fp);
    close(fp->fileno);
    free(fp);
}
int _fflush(_FILE* fp){
    if(fp->outpos){
        write(fp->fileno,fp->outbuffer,fp->outpos);
        fp->outpos=0;
    }
    return 0;
}

